<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\api\controller\v1\user;

use app\Request;
use app\services\product\product\StoreProductLogServices;
use app\services\user\UserCancelServices;
use app\services\user\UserServices;
use app\services\wechat\WechatUserServices;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;
use think\facade\Db;


/**
 * 用户类
 * Class UserController
 * @package app\api\controller\store
 */
class UserController
{
    protected $services = NUll;

    /**
     * UserController constructor.
     * @param UserServices $services
     */
    public function __construct(UserServices $services)
    {
        $this->services = $services;
    }

    /**
     * 获取用户信息
     * @param Request $request
     * @return mixed
     */
    public function userInfo(Request $request)
    {
        $info = $request->user()->toArray();
        return app('json')->success($this->services->userInfo($info));
    }

    /**
     * 用户资金统计
     * @param Request $request
     * @return mixed
     */
    public function balance(Request $request)
    {
        $uid = (int)$request->uid();
        return app('json')->success($this->services->balance($uid));
    }

    /**
     * 个人中心
     * @param Request $request
     * @return mixed
     */
    public function user(Request $request)
    {
        $user = $request->user()->toArray();
        return app('json')->success($this->services->personalHome($user, $request->tokenData()));
    }

    /**
     * 获取最新订单
     * @param Request $request
     * @return mixed
     */
    public function get_order_status(Request $request){
        $user = $request->user()->toArray();
        //查询最新订单状态
        $check_order = Db::name('car_order')->field('id,status')->where('uid',$user['uid'])->group('status')->order('status asc')->select()->toArray();
        if($check_order){
            $order_status = $check_order[0]['status'];
        }else{
            $order_status = 0;
        }
        return app('json')->success(['order_status'=>$order_status]);

    }
    /**
     * 获取活动状态
     * @return mixed
     */
    public function activity()
    {
        return app('json')->success($this->services->activity());
    }

    /**
     * 用户修改信息
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request)
    {
        list($avatar, $nickname,$phone) = $request->postMore([
            ['avatar', ''],
            ['nickname', ''],
            ['phone','']
        ], true);
        if (!$avatar && $nickname == ''&& $phone == '') {
            return app('json')->fail(410134);
        }
        $uid = (int)$request->uid();
        if ($this->services->eidtNickname($uid, ['avatar' => $avatar, 'nickname' => $nickname,'phone'=>$phone])) {
            return app('json')->success(100014);
        }
        return app('json')->fail(100015);
    }

    /**
     * 推广人排行
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function rank(Request $request)
    {
        $data = $request->getMore([
            ['page', ''],
            ['limit', ''],
            ['type', '']
        ]);
        return app('json')->success($this->services->getRankList($data));
    }

    /**
     * 添加访问记录
     * @param Request $request
     * @return mixed
     */
    public function set_visit(Request $request)
    {
        $data = $request->postMore([
            ['url', ''],
            ['stay_time', 0]
        ]);
        if ($data['url'] == '') return app('json')->fail(100100);
        $data['uid'] = (int)$request->uid();
        $data['ip'] = $request->ip();
        if ($this->services->setVisit($data)) {
            return app('json')->success(100021);
        } else {
            return app('json')->fail(100022);
        }
    }

    /**
     * 静默绑定推广人
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function spread(Request $request)
    {
        [$spreadUid, $code] = $request->postMore([
            ['puid', 0],
            ['code', 0]
        ], true);
        $uid = (int)$request->uid();
        $res = $this->services->spread($uid, (int)$spreadUid, $code);
        return app('json')->success($res);
    }

    /**
     * 推荐用户
     * @param Request $request
     * @return mixed
     */
    public function spread_people(Request $request)
    {
        $spreadInfo = $request->postMore([
            ['grade', 0],
            ['keyword', ''],
            ['sort', ''],
        ]);
        if (!in_array($spreadInfo['grade'], [0, 1])) {
            return app('json')->fail(100100);
        }
        $uid = $request->uid();
        return app('json')->success($this->services->getUserSpreadGrade($uid, $spreadInfo['grade'], $spreadInfo['sort'], $spreadInfo['keyword']));
    }

    /**
     * 是否关注
     * @param Request $request
     * @return mixed
     */
    public function subscribe(Request $request)
    {
        if ($request->uid()) {
            /** @var WechatUserServices $wechatUserService */
            $wechatUserService = app()->make(WechatUserServices::class);
            $subscribe = (bool)$wechatUserService->value(['uid' => $request->uid()], 'subscribe');
            return app('json')->success(['subscribe' => $subscribe]);
        } else {
            return app('json')->success(['subscribe' => true]);
        }
    }

    /**
     * 用户注销
     * @param Request $request
     * @return mixed
     */
    public function SetUserCancel(Request $request)
    {
        /** @var UserCancelServices $userCancelServices */
        $userCancelServices = app()->make(UserCancelServices::class);
        $userCancelServices->SetUserCancel($request->uid());
        return app('json')->success(410135);
    }

    /**
     * 商品浏览记录
     * @param Request $request
     * @param StoreProductLogServices $services
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function visitList(Request $request, StoreProductLogServices $services)
    {
        $where['uid'] = (int)$request->uid();
        $where['type'] = 'visit';
        $result = $services->getList($where, 'product_id', 'id,product_id,max(add_time) as add_time');
        $time_data = [];
        if ($result['list']) {
            foreach ($result['list'] as $key => &$item) {
                $add_time = strtotime($item['add_time']);
                if (date('Y') == date('Y', $add_time)) {//今年
                    $item['time_key'] = date('m-d', $add_time);
                } else {
                    $item['time_key'] = date('Y-m-d', $add_time);
                }
            }
            $time_data = array_merge(array_unique(array_column($result['list'], 'time_key')));
        }
        $result['time'] = $time_data;
        return app('json')->success($result);
    }

    /**
     * 商品浏览记录删除
     * @param Request $request
     * @param StoreProductLogServices $services
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function visitDelete(Request $request, StoreProductLogServices $services)
    {
        $uid = (int)$request->uid();
        [$ids] = $request->postMore([
            ['ids', []],
        ], true);
        if ($ids) {
            $where = ['uid' => $uid, 'product_id' => $ids];
            $services->delete($where);
        }
        return app('json')->success('删除成功');
    }

    /**
     * 修改用户信息
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function submitUser(Request $request){
        $data = $request->postMore([
            ['avatar',''],
            ['nickname',''],
            ['sex',''],
            ['phone',''],
            ['city','']
        ]);
        if(!$data['nickname']) return app('json')->fail('请输入昵称');
        $uid = $request->uid();
        return app('json')->success($this->services->submitUser($uid,$data));
    }

    /**
     * 获取推广人
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function spread_people_car(Request $request){
        $data = $request->postMore([
            ['grade',0],
            ['keyword',''],
            ['sort','']
        ]);
        if(!in_array($data['grade'],[0,1])) return app('json')->fail('参数错误');
        $uid = (int)$request->uid();
        return app('json')->success($this->services->spread_people_car($uid,$data));
    }


    //获取约你游app的用户信息
    public function get_yny_userinfo(){
        $phone = 17611111133;
        $time = time();
        $str = 'mobile='.$phone.'&time='.$time;
        $sign = MD5($str);
        $url = 'https://apiv2.t.xindiantv.com/api/member/third/GetMemberByMobile?mobile='.$phone.'&time='.$time.'&sign='.$sign;
        $ret = doCurlGetRequest($url);
        $ret = json_decode($ret,true);
        p($ret);exit;
    }

    //查询当前用户有没有待处理违章数据
    public function get_userwz(Request $request){
        $data = $request->getMore([
            ['uid',0],
        ]);
        if($data['uid']>0){
            if(!$data['uid'])return app('json')->fail('参数错误');
            $data = Db::name('car_wz')->where('status',1)->where('uid',$data['uid'])->order('id desc')->find();
            if(!$data){
                $data = [];
            }
        }else{
            $data = [];
        }
        return app('json')->success($data);
    }

    //查询当前用户待处理违章列表
    public function get_userwz_list(Request $request)
    {
        $data = $request->getMore([
            ['uid',0],
        ]);
        $page = input("page","1","intval");
        $size = 10;
        $status = input("status",'');
        $order_id = input('order_id','');
        if(!$order_id)return app('json')->fail('参数错误！');
        $where = [];
        if($status||$status==0&&$status!=""){
            $where[] = ['r.status','=',$status];
            if($status==1){
                $where[] = ['r.illegal_return_type','=',3];
            }elseif($status==2){
                $where[] = ['r.illegal_return_type','in','1,2'];
            }
        }
        if($order_id){
            $where[] = ['order_id','=',$order_id];
        }
        $car_order = Db::name('car_wz')
            ->alias('r')
            ->join('car_order o','r.order_id=o.id','left')
            ->join('car_order_take t','t.id=o.take_id','left')
            ->join('base_place p','p.id=r.store_id','left')
            ->field('r.illegal_remark,r.id,o.order_no,r.wz_img_array,r.wz_sub_time,r.status,o.contact_name,o.contact_mobile,t.car_no,t.car_id,o.type_name,r.wz_ok_time,p.contact_tel,o.return_id,r.amount')
            ->where($where)
            ->order('r.id desc')
            ->limit((($page - 1) * $size),$size)
            ->select()->toArray();
        foreach($car_order as $k=>$v){
            if($v["wz_sub_time"]){
                $car_order[$k]['wz_sub_time'] = date('Y-m-d H:i:s',$v['wz_sub_time']);
            }
            if($v["wz_ok_time"]){
                $car_order[$k]['wz_ok_time'] = date('Y-m-d H:i:s',$v['wz_ok_time']);
            }
            if($v['return_id']){
                $car_order_return = Db::name('car_order_return')->where('id',$v['return_id'])->find();
                if($car_order_return){
                    $time = $car_order_return['add_time']+1296000;
                    $countdown = $time - time();
                    $countdown = floor($countdown/86400);
                    $car_order[$k]['countdown'] = $countdown."天";
                    if($countdown<0){
                        $car_order[$k]['countdown'] ="";
                    }
                }
            }else{
                $car_order[$k]['countdown']="";
            }
        }
        $car_num = count($car_order);
        $res['list'] = $car_order;
        $res["page"]=$page;
        $res["total"]=$car_num;
        $res["size"]=$size;
        return app('json')->success($res);
    }
    public function check_phone(Request $request){
        $data = $request->getMore([
            ['phone',0],
            ['uid',0],
        ]);
        if(!$data['phone'])return app('json')->fail('手机号为空！');
        if(!$data['uid'])return app('json')->fail('uid为空！');
        $check = Db::name('user')->field('uid,phone,nickname')->where('phone',$data['phone'])->find();
        if($check['uid']==$data['uid'])return app('json')->fail('赠送人不能选取自己！');
        return  app('json')->status('success', '请求成功', $check);
    }
}
